package com.qf.session;

import com.qf.pickname.entity.Student;
import org.apache.catalina.Session;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
@RequestMapping("/session")
public class SessionController {

    @RequestMapping("/get/{name}")
    public Student getStudent(@PathVariable("name") String name, HttpSession session) {
        // 希望这个接口只有用户登录后才可以访问
        Object username = session.getAttribute("username");
        if (username == null) {
            throw new RuntimeException("没有登录无法访问该接口");
        }
        Student student = new Student();
        student.setName(name);
        student.setSex("男");
        return student;
    }


    @RequestMapping("/login")
    public HashMap<String, Object> login(String name, String pwd, HttpSession session) {

        HashMap<String, Object> hashMap = new HashMap<>();

        if (name.equals("admin") && pwd.equals("123456")) {
            hashMap.put("code", 1);
            hashMap.put("msg", "登录成功");
            // 向session对象中放入用户名，证明该用户曾经登录成功过
            session.setAttribute("username", name);
            return hashMap;
        } else {
            hashMap.put("code", -1);
            hashMap.put("msg", "登录失败");
            return hashMap;
        }

    }

}
